package com.zhengqiangblog.blog.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.zhengqiangblog.blog.dao.common.JdbcDaoSupport;
import com.zhengqiangblog.blog.model.ArticleTag;
import com.zhengqiangblog.blog.model.HotTag;
import com.zhengqiangblog.core.RowMapper;

public class ArticleTagDao extends JdbcDaoSupport {

	private static final Logger logger = Logger.getLogger(ArticleTagDao.class);

	private ArticleTagRowMapper articleTagRowMapper = new ArticleTagRowMapper();

	public ArticleTagDao() {
		logger.info("ArticleTagDao initializing...");
	}

	public int saveArticleTag(ArticleTag articleTag) throws Exception {
		String sql = "insert into article_tag (article_id, tag_id) values (?, ?)";
		return this.getJdbcTemplate().update(sql, articleTag.getArticleId(), articleTag.getTagId());
	}

	public List<ArticleTag> getArticleTagByArticle(int articleId) throws Exception {
		String sql = "select * from article_tag where article_id = ?";
		return this.getJdbcTemplate().query(sql, articleTagRowMapper, articleId);
	}

	public List<Integer> getArticleIdListByTagId(int tagId) throws Exception {
		String sql = "select article_id from article_tag where tag_id = ? order by article_id desc";
		return this.getJdbcTemplate().query(sql, new RowMapper<Integer>() {
			@Override
			public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
				return rs.getInt("article_id");
			}
		}, tagId);
	}

	public int deleteArticleTag(int articleId, int tagId) throws Exception {
		String sql = "delete from article_tag where article_id = ? and tag_id = ?";
		return this.getJdbcTemplate().update(sql, articleId, tagId);
	}

	public int deleteArticleTagByArticle(int articleId) throws Exception {
		String sql = "delete from article_tag where article_id = ?";
		return this.getJdbcTemplate().update(sql, articleId);
	}

	public List<HotTag> getHotTags(int size) throws Exception {
		String sql = "select tag_id, count(article_id) as count from article_tag "
				+ "group by tag_id order by count desc, tag_id asc limit ?";
		return this.getJdbcTemplate().query(sql, new RowMapper<HotTag>() {
			@Override
			public HotTag mapRow(ResultSet rs, int rowNum) throws SQLException {
				HotTag hotTag = new HotTag();
				hotTag.setTagId(rs.getInt("tag_id"));
				hotTag.setArticles(rs.getInt("count"));
				return hotTag;
			}
		}, size);
	}

	private class ArticleTagRowMapper implements RowMapper<ArticleTag> {
		@Override
		public ArticleTag mapRow(ResultSet rs, int rowNum) throws SQLException {
			ArticleTag articleTag = new ArticleTag();
			articleTag.setId(rs.getInt("id"));
			articleTag.setArticleId(rs.getInt("article_id"));
			articleTag.setTagId(rs.getInt("tag_id"));
			return articleTag;
		}
	}

}
